 /**
 * Description: 物资借出记录
 * @author:Hunter
 * @since:1.0.0
 *
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-04-08   Hunter       1.0.0     Initial
 */
package com.metro.paperless.app.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.metro.core.dao.IMapper;
import com.metro.core.service.BaseServiceSupport;
import com.metro.core.service.ServiceException;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;
import com.metro.paperless.app.beans.vo.AppLendDetail;
import com.metro.paperless.app.beans.vo.AppLendDetailForm;
import com.metro.paperless.app.beans.vo.AppMaterialsLend;
import com.metro.paperless.app.mapper.IAppLendDetailMapper;
import com.metro.paperless.app.mapper.IAppMaterialsLendMapper;
import com.metro.paperless.app.service.inf.IAppLendDetailService;
import com.metro.paperless.app.service.inf.IAppMaterialsLendService;
import com.metro.paperless.biz.beans.vo.BizMaterialsManage;
import com.metro.paperless.biz.mapper.IBizMaterialsManageMapper;
import com.metro.paperless.biz.service.inf.IBizMaterialsManageService;

 /**
 * 物资借出记录<br>
 *
 * @author:Hunter
 * @since:1.0.0
 * @version [1.0.0, 2018-04-08]
 */
@Service("appmaterialslendService")
public class AppMaterialsLendService extends BaseServiceSupport<AppMaterialsLend> implements IAppMaterialsLendService{
    //物资借出记录Mapper
    @Autowired
    private IAppMaterialsLendMapper appmaterialslendMapper;
    @Autowired
    private IAppLendDetailMapper appLendDetailMapper;
//    @Autowired
//    private IAppLendDetailService lendDetailService;
    @Autowired
    private IAppLendDetailMapper lendDetailMapper;
//    @Autowired
//    private IBizMaterialsManageService materialsManageService;
    @Autowired
    private IBizMaterialsManageMapper materialsManageMapper;

    @SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
    public IMapper getMapper() {
        return appmaterialslendMapper;
    }

    @Override
    public IResult save(AppMaterialsLend entity) {
        try {
            appmaterialslendMapper.save(entity);
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("新增物资借出记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
    }

    @Override
    public IResult update(AppMaterialsLend entity) {
        try {
            appmaterialslendMapper.update(entity);
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("修改物资借出记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
    }

    @Override
    public IResult delete(Long id) {
        try {
            appmaterialslendMapper.delete(id);
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("删除失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
    }

    @Override
    public IResult deleteByIds(String ids) {
        try {
            appmaterialslendMapper.deleteByIds(ids);
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("删除失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
    }

	@Override
	public IResult save(AppLendDetailForm form, AppMaterialsLend entity) {
		try {
            entity.setActionTime(new Date());
            //保存时状态为待出借
            entity.setLendStatus("0");
            appmaterialslendMapper.save(entity);
            Long lendId = entity.getId();
            for (AppLendDetail itementity : form.getItemEntity()) {
                itementity.setLendId(lendId);
                //保存时状态为待出借
                itementity.setLendStatus("0");
                itementity.setNeedReturnNum(itementity.getLendNum());
                appLendDetailMapper.save(itementity);
                Long matId = itementity.getMaterialsId();
                BizMaterialsManage materialsManage = materialsManageMapper.getById(matId);
                int enableStockNum = materialsManage.getEnableStockNum();
                int outNum = itementity.getLendNum();
                if(itementity.getLendNum() < enableStockNum){
                    enableStockNum  = enableStockNum - outNum;
                    materialsManage.setEnableStockNum(enableStockNum);
                    materialsManageMapper.update(materialsManage);
                }
            }
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("新增物资出借记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
	}
	
	@Override
	public JsonResult saveOther(AppLendDetailForm form, AppMaterialsLend entity) {
		try{
			JsonResult jr = new JsonResult();
			entity.setActionTime(new Date());
			//保存时状态为待出借
	        entity.setLendStatus("0");
	        appmaterialslendMapper.save(entity);
	        Long lendId = entity.getId();
	        // TODO 循环插入效率低，待优化(batch)
	        for (AppLendDetail itementity : form.getItemEntity()) {
	            itementity.setLendId(lendId);
	            //保存时状态为待出借
	            itementity.setLendStatus("0");
	            itementity.setNeedReturnNum(itementity.getLendNum());
	            appLendDetailMapper.save(itementity);
	            Long matId = itementity.getMaterialsId();
                BizMaterialsManage materialsManage = materialsManageMapper.getById(matId);
                int enableStockNum = materialsManage.getEnableStockNum();
                int lendNum = itementity.getLendNum();
                //保存的时候改变可用库存
                if(itementity.getLendNum() <= enableStockNum){
                    enableStockNum  = enableStockNum - lendNum;
                    materialsManage.setEnableStockNum(enableStockNum);
                    materialsManageMapper.update(materialsManage);
                }
	        }
	        jr.setData(lendId);
	        jr.setResult(ResultCode.SUCCESS);
			return jr;
		}catch(Exception e){
			log.error("新增物资出借记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
		}
		
	}

	@Override
	public IResult update(AppLendDetailForm form, AppMaterialsLend materialsLend) {
		try{
			AppMaterialsLend entity = appmaterialslendMapper.getById(materialsLend.getId());
			entity.setLendTitle(materialsLend.getLendTitle());
			entity.setOrgId(materialsLend.getOrgId());
			entity.setOrgName(materialsLend.getOrgName());
			entity.setGrantOrgId(materialsLend.getGrantOrgId());
			entity.setGrantOrgName(materialsLend.getGrantOrgName());
			entity.setAgentName(materialsLend.getAgentName());
			appmaterialslendMapper.update(entity);
			//更新的时候直接删除对应出借单明细,再添加新数据
			//删除之后要更新相应物资的可用库存
			List<AppLendDetail> list = lendDetailMapper.getByLendId(materialsLend.getId());
			for(AppLendDetail detail : list){
				lendDetailMapper.delete(detail.getId());
				BizMaterialsManage manager =  materialsManageMapper.getById(detail.getMaterialsId());
				manager.setEnableStockNum(manager.getEnableStockNum() + detail.getLendNum());
				materialsManageMapper.update(manager);
			}
			
			for (AppLendDetail itementity : form.getItemEntity()) {
				//直接保存接收到的数据
				itementity.setLendStatus("0");
				itementity.setLendId(materialsLend.getId());
				itementity.setNeedReturnNum(itementity.getLendNum());
                appLendDetailMapper.save(itementity);
                Long matId = itementity.getMaterialsId();
                BizMaterialsManage materialsManage = materialsManageMapper.getById(matId);
                int enableStockNum = materialsManage.getEnableStockNum();
                int lendNum = itementity.getLendNum();
                //改变可用库存,此处修改可用库存要注意
                if(itementity.getLendNum() <= enableStockNum){
                    enableStockNum  = enableStockNum - lendNum;
                    materialsManage.setEnableStockNum(enableStockNum);
                    materialsManageMapper.update(materialsManage);
                }
            }
			return ResultCode.SUCCESS;
		}catch(Exception e){
			log.error("修改出借记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
		}
	}

	@Override
	public IResult updateMateAndLend(AppMaterialsLend materialsLend, List<AppLendDetail> appLendDetailList) {
		try{

			//借出成功，设置为待还状态
			materialsLend.setLendStatus("1");
			appmaterialslendMapper.update(materialsLend);
			for(AppLendDetail item: appLendDetailList){
				//设置出借详情状态为待还
				item.setLendStatus("1");
				BizMaterialsManage materialsManage = materialsManageMapper.getById(item.getMaterialsId());
				//修改物资的实际库存
				materialsManage.setStockNum(materialsManage.getStockNum() - item.getLendNum());
				appLendDetailMapper.update(item);
				materialsManageMapper.update(materialsManage);
			}
			return ResultCode.SUCCESS;
		}catch(Exception e){
			log.error("修改出借记录的状态和出借物资详情的状态以及物资的库存", e);
            throw new ServiceException(ResultCode.ERROR);
		}
		
	}

	@Override
	public IResult deleteLendAndDetail(Long lendId) {
		try{
			log.error("删除出借记录");
			appmaterialslendMapper.delete(lendId);
			AppLendDetail params = new AppLendDetail();
			params.setLendId(lendId);
			List<AppLendDetail> list = lendDetailMapper.getByLendId(lendId);
			//TODO 循环删除太low,待优化(batch)
			for(AppLendDetail item : list){
				log.error("【删除出借明细】");
				//删除时，修改物资的可用库存
				BizMaterialsManage materialsManage = materialsManageMapper.getById(item.getMaterialsId());
				log.error("【" + materialsManage.getMaterialsName() +  "】");
				log.error("原有可用库存---->>>>" + materialsManage.getEnableStockNum());
				materialsManage.setEnableStockNum(materialsManage.getEnableStockNum() + item.getLendNum());
				log.error("现有可用库存---->>>>" +  materialsManage.getEnableStockNum());
				materialsManageMapper.update(materialsManage);
				lendDetailMapper.delete(item.getId());
			}
			return ResultCode.SUCCESS;
		}catch(Exception e){
			log.error("删除出借记录和出借详情", e);
            throw new ServiceException(ResultCode.ERROR);
		}
	}
}